package com.only4play.iot.system.util;

import cn.hutool.core.util.StrUtil;
import com.only4play.iot.system.pojo.SysMenu;
import com.only4play.iot.web.base.BaseEntity;
import org.springframework.util.StringUtils;

import java.util.List;
import java.util.Map;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.stream.Collectors;

/**
 * @author mengdy
 */
public class MenuUtil {

    public static List<SysMenu> treeMenuBySpecial(List<SysMenu> menus) {

        // 分桶分级
        Map<Long, List<SysMenu>> menuMap = menus.stream().collect(Collectors.groupingBy(SysMenu::getParentId));
        // 获取所有菜单与父级的键值对
        Map<Long, Long> menuKeyAndValue = menus.stream().collect(Collectors.toMap(BaseEntity::getId, SysMenu::getParentId));
        List<SysMenu> sysMenuListNew = menus.stream().peek(sysMenu -> {
            // 获取类型为2且组件名称不为空的菜单
            if (sysMenu.getType() == 2 && !StrUtil.isEmpty(sysMenu.getComponent())) {
                sysMenu.setParentId(menuKeyAndValue.get(sysMenu.getParentId()));
            }
        }).toList();

        return menuMap.get(0L).stream().map(top -> {
            return MenuUtil.findChildrenMenu(top, sysMenuListNew);
        }).collect(Collectors.toList());
    }

    private static SysMenu findChildrenMenu(SysMenu sysMenu, List<SysMenu> sysMenuList) {
        // 子菜单初始化
        List<SysMenu> childrenMenus = new CopyOnWriteArrayList<>();
        // 遍历菜单
        sysMenuList.forEach(menu -> {
            if (sysMenu.getId().equals(menu.getParentId())){
                childrenMenus.add(findChildrenMenu(menu, sysMenuList));
            }
        });
        sysMenu.setChildren(childrenMenus);
        return sysMenu;
    }
}
